<template>
  <div class="courses-page">
    <el-card class="search-filter-card">
      <el-row :gutter="20" align="middle">
        <el-col :span="18">
          <el-input
            v-model="searchQuery"
            placeholder="搜索课程..."
            :prefix-icon="Search"
            clearable
          />
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="applyFilter">搜索</el-button>
        </el-col>
      </el-row>
      
      <div class="category-section">
        <div class="category-level">
          <span class="category-label">分类：</span>
          <div class="category-tags-container">
            <span 
              class="category-tag" 
              :class="{'selected-tag': selectedCategory === '全部'}"
              @click="selectCategory('全部')"
            >全部</span>
            <span 
              v-for="category in categories" 
              :key="category"
              class="category-tag"
              :class="{'selected-tag': selectedCategory === category}"
              @click="selectCategory(category)"
            >{{ category }}</span>
          </div>
        </div>
      </div>
    </el-card>

    <el-row :gutter="20" class="course-list-grid" v-loading="loading">
      <el-col :span="6" v-for="course in filteredCourses" :key="course.courseID" class="course-col">
        <el-card :body-style="{ padding: '0px' }" class="course-card" @click="goToCourseDetail(course.courseID)">
          <img :src="course.img || 'https://via.placeholder.com/200x150'" class="image" />
          <div style="padding: 14px">
            <span class="course-name">{{ course.name }}</span>
            <div class="course-meta">
              <span class="course-price" :class="{ 'free': course.price === 0 }">
                {{ course.price === 0 ? '免费' : '¥' + course.price.toFixed(2) }}
              </span>
            </div>
            <div class="bottom">
              <div class="course-actions">
                <el-button 
                  type="primary" 
                  size="small"
                  @click.stop="goToCourseDetail(course.courseID)"
                >
                  查看详情
                </el-button>
                <el-button 
                  v-if="course.price > 0"
                  type="danger" 
                  size="small"
                  @click.stop="handlePurchaseCourse(course)"
                >
                  立即购买
                </el-button>
                <el-button 
                  v-else
                  type="success" 
                  size="small"
                  @click.stop="goToCourseDetail(course.courseID)"
                >
                  免费学习
                </el-button>
              </div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-empty v-if="!loading && filteredCourses.length === 0" description="暂无课程"></el-empty>
    </el-row>

    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalCourses"
        :page-size="pageSize"
        v-model:current-page="currentPage"
        @current-change="handlePageChange"
      ></el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { Search, Star } from '@element-plus/icons-vue'
import { getCourseList, searchCourses, purchaseCourse as purchaseCourseAPI } from '../api/course'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'

const router = useRouter()
const userStore = useUserStore()

const searchQuery = ref('')
const selectedCategory = ref('全部')
const categories = ref([])

// 从课程数据中提取分类
const extractCategories = (courses) => {
  const categorySet = new Set()
  courses.forEach(course => {
    if (course.category && Array.isArray(course.category)) {
      course.category.forEach(cat => categorySet.add(cat))
    }
  })
  return Array.from(categorySet)
}

// 获取所有分类
const fetchAllCategories = async () => {
  try {
    // 获取所有课程（不分页）来提取分类
    const res = await getCourseList({
      page: 1,
      pageSize: 9999 // 设置一个足够大的数字以获取所有课程
    })
    if (res.code === 1) {
      const allCourses = res.data.items || []
      categories.value = extractCategories(allCourses)
    }
  } catch (error) {
    console.error('Failed to fetch categories:', error)
    ElMessage.error('获取分类信息失败，请重试')
  }
}

const courses = ref([])
const currentPage = ref(1)
const pageSize = ref(8)
const loading = ref(false)

// 分类和分页全部在前端完成
const filteredCourses = computed(() => {
  let filtered = courses.value
  if (selectedCategory.value !== '全部') {
    filtered = filtered.filter(course =>
      course.category &&
      Array.isArray(course.category) &&
      course.category.includes(selectedCategory.value)
    )
  }
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filtered.slice(start, end)
})

const totalCourses = computed(() => {
  if (selectedCategory.value === '全部') {
    return courses.value.length
  }
  return courses.value.filter(course =>
    course.category &&
    Array.isArray(course.category) &&
    course.category.includes(selectedCategory.value)
  ).length
})

const selectCategory = (category) => {
  selectedCategory.value = category
  currentPage.value = 1 // 切换分类时重置页码
}

const handlePageChange = (newPage) => {
  currentPage.value = newPage
}

const fetchCourses = async () => {
  loading.value = true
  try {
    // 获取所有课程，不分页
    const res = await getCourseList({
      page: 1,
      pageSize: 9999
    })
    if (res.code === 1) {
      courses.value = res.data.items || []
    } else {
      ElMessage.error(res.message || '获取课程失败')
      courses.value = []
    }
  } catch (error) {
    console.error('Failed to fetch courses:', error)
    ElMessage.error(error.message || '获取课程失败，请重试')
    courses.value = []
  } finally {
    loading.value = false
  }
}

const applyFilter = () => {
  currentPage.value = 1
  fetchCourses()
}

const goToCourseDetail = (courseId) => {
  router.push(`/course/${courseId}`)
}

const handlePurchaseCourse = async (course) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录后再购买课程')
    router.push('/login')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定购买课程"${course.name}"吗？价格：¥${course.price}`,
      '购买确认',
      {
        confirmButtonText: '确定购买',
        cancelButtonText: '取消',
        type: 'warning',
        center: true,
        roundButton: true
      }
    )
    
    const res = await purchaseCourseAPI(course.courseID)
    if (res.code === 1) {
      ElMessage.success('课程购买成功！')
      // 可以跳转到课程详情页或我的课程页面
      router.push(`/course/${course.courseID}`)
    } else {
      ElMessage.error(res.message || '购买失败，请重试')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '购买失败，请稍后再试')
      console.error('Purchase error:', error)
    }
  }
}

onMounted(() => {
  fetchAllCategories()
  fetchCourses()
})
</script>

<style scoped>
.courses-page {
  width: 70vw;
  padding: 20px;
}

.search-filter-card {
  margin-bottom: 20px;
  padding: 20px;
}

.course-list-grid {
  margin-top: 20px;
}

.category-section {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.category-level {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.category-label {
  font-weight: bold;
  margin-right: 10px;
  min-width: 60px;
}

.category-tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.category-tag {
  padding: 5px 15px;
  border-radius: 15px;
  background-color: #f5f7fa;
  color: #606266;
  cursor: pointer;
  transition: all 0.3s;
}

.category-tag:hover {
  background-color: #ecf5ff;
  color: #409EFF;
}

.selected-tag {
  background-color: #409EFF;
  color: white;
}

.course-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: transform 0.3s;
}

.course-card:hover {
  transform: translateY(-5px);
}

.image {
  width: 100%;
  height: 150px;
  object-fit: cover;
}

.course-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  display: block;
  min-height: 48px; /* 确保标题区域有固定高度，防止错位 */
}

.course-meta {
  margin-top: 10px;
  margin-bottom: 10px; /* 为按钮留出空间 */
}

.course-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

.course-price.free {
  color: #67c23a;
}

.bottom {
  margin-top: 13px;
  line-height: 12px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-actions {
  display: flex;
  justify-content: flex-end; /* 让按钮组靠右对齐 */
  width: 100%;
  gap: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 